import { Component, OnInit } from '@angular/core';

import { NzMessageService } from 'ng-zorro-antd/message';

import { AppManagementService } from './app-management.service';
import {PermissionService} from '../../../service/permission.service';
import { CommonService } from 'src/app/services-common/common.service';
import { defalutImg } from 'src/app/comm';
import { NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-management',
  templateUrl: './app-management.component.html',
  styleUrls: ['./app-management.component.scss']
})
export class AppManagementComponent implements OnInit {
  fallbackImg: string = defalutImg;
  queryForm: any = {
    // 当前页码
    pageNum: 1,
    // 分页大小
    pageSize: 10,
  }
  // 一 二 三 级 弹窗对象
  modalForm: any = {
    type: '1'
  }
  // 原始数据
  modalFormBase: any = {
    // 0 1 禁用 启用
    status: 1,
    // 适用用户
    userType: '0'
  }
  // 上传列表集合
  fileList: any = []
  /**
   * 表单load加载
   */
  tableLoading: any = false;
  // 列表数据
  tableData: any = {
    // 数据列表集合
    records: [],
    // 总条数
    total: 0
  }

  // 一级弹窗
  isOneModalShow: boolean = false
  // 二级弹窗
  isTwoModalShow: boolean = false
  // 三级弹窗
  isThreeModalShow: boolean = false

  // 上级分类
  categoryList: any = []

  /**
   * 全局 loading
   */
  messageId: any = null;

  // 防止重复上传
  forbidUpload: boolean = false

  // 定时器
  time: any = null

  // 适用用户设置默认值
  bUserType: boolean = true

  cUserType: boolean = true
  // 缓存
  cacheData: any = {
    // 一、二、三级弹窗
    level: '',
  }
  // 跳转方式集合
  typeSet: any = { 1: '商品ID', 2: '链接', 3: '搜索', 4: '分类' }
  // 时间定时器
  timeout: any = null

  mappingOptions: any = [];
  channeloptions: any = [];
  channelChecked: any = [];

  urlChecked: boolean = false;

  // 适用终端checked
  terminalAllChecked = false;
  terminalIndeterminate = true;

  /**
   * ----------------------------------------------------------------
   * 关联商品
   * ----------------------------------------------------------------
   */
  // 关联商品 Modal
  isRelationVisible: boolean = false;
  relationGoodType: number = 0;
  relationGoodItem: any = null;
  goodTableParams = {
    loading: false,
    page: 1,
    pageSize: 10,
    total: 0,
    name: ''
  };
  goodTable: any = [];
  subRelationGoodLoading: boolean = false;
  // 关联商品 勾选
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  listOfData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  setOfCheckedArr: any = [];

  constructor(
    private AppManagementService: AppManagementService,
    private message: NzMessageService,
    public permission: PermissionService,
    private nzModal: NzModalService,
    private commonService: CommonService
  ) { }

  ngOnInit() {
    this.getMappingData()
    this.getChanneloptions()
    this.httpList()
  }

  // 获取映射list
  async getMappingData() {
    let params = {
      page: 1,
      pageSize: 10000
    }
    const res: any = await this.commonService.getMappingData(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.mappingOptions = records || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 获取适用终端(字典channel)
  async getChanneloptions() {
    this.channeloptions = [];
    const res: any = await this.commonService.dictListData('channel');
    if (res.code === 0) {
      const { list } = res.data || {};

      if (list?.length) {
        list.forEach((item: any) => {
          if (item.status === 1) {
            this.channeloptions.push({
              value: item.content,
              label: item.name,
              checked: false
            })
          }
        })
      }
    } else {
      this.message.error(res.message);
    }
  }

  // 适用终端单选
  channelChange(value: string[]) {
    if (this.channeloptions.every((item: any) => !item.checked)) {
      this.terminalAllChecked = false;
      this.terminalIndeterminate = false;
    } else if (this.channeloptions.every((item: any) => item.checked)) {
      this.terminalAllChecked = true;
      this.terminalIndeterminate = false;
    } else {
      this.terminalIndeterminate = true;
    }

    this.channelChecked = value;
  }

  // 适用终端全选全不选
  terminalUpdateAllChecked() {
    this.terminalIndeterminate = false;
    if (this.terminalAllChecked) {
      this.channeloptions = this.channeloptions.map((item: any) => ({
        ...item,
        checked: true
      }));
    } else {
      this.channeloptions = this.channeloptions.map((item: any) => ({
        ...item,
        checked: false
      }));
    }

    this.channelChecked = this.channeloptions.filter((item: any) => item.checked).map((tag: any) => tag.value);
  }

  // 查询列表
  onQuery() {
    this.queryForm.pageNum = 1
    this.httpList()
  }
  /**
   * 页码改变
   * @param index 页码数
   */
  onPageIndexChange(index: Number) {
    this.queryForm.pageNum = index;
    this.httpList()
  }
  /**
   * 每页条数改变的回调
   * @param index 页码数
   */
  onPageSizeChange(index: Number) {
    this.queryForm.pageSize = index;
    this.httpList()
  }
  // 一级新增
  onOpenOneModalAdd() {
    this.modalForm = { ...this.modalFormBase }
    this.channeloptions.map((item: any) => item.checked = true);

    // 适用终端全选or全不选
    if (this.channeloptions.every((item: any) => !item.checked)) {
      this.terminalAllChecked = false;
      this.terminalIndeterminate = false;
    } else if (this.channeloptions.every((item: any) => item.checked)) {
      this.terminalAllChecked = true;
      this.terminalIndeterminate = false;
    } else {
      this.terminalIndeterminate = true;
    }
    this.channelChecked = this.channeloptions.map((tag: any) => tag.value);
    this.isOneModalShow = true
  }
  // 二级新增
  onOpenTwoModalAdd() {
    this.modalForm = { ...this.modalFormBase }
    this.isTwoModalShow = true
    this.httpCategoryParent(1) // 一级数据
  }
  // 三级新增
  onOpenThreeModalAdd() {
    this.modalForm = { ...this.modalFormBase, userType: 0 }
    this.isThreeModalShow = true
    this.httpCategoryParent(2)// 二级数据
  }
  // 关闭新增弹窗
  onModalClose() {
    this.isOneModalShow = false
    this.isTwoModalShow = false
    this.isThreeModalShow = false
  }
  // 上传图标和角标的按钮
  onModalPreview(ev: any) {
    const { originFileObj } = ev?.file
    this.httpUpload(originFileObj)
  }
  // 删除上传图片
  onDelectImg() {
    this.modalForm.icon = ''
  }
  // 适用用户
  logUserType(value: string[]): void {

    if (value) {
      this.modalForm.userType = value.join(',')
    }
    if (value.length == 2) { // 同事选择 b c 端 转成 0普通用户
      this.modalForm.userType = '0'
    }
  }
  // 控制是否显示二级目录
  onTableOneItem(item: any) {
    const { list } = item
    if (!list || list.length <= 0) {
      return
    }
    item.isShow = !item.isShow
  }
  // 控制是否显示三级级目录
  onTableSecondItem(item: any) {
    const { list } = item
    if (!list || list.length <= 0) {
      return
    }
    item.isShow = !item.isShow
  }
  // 列表删除 status 2
  onTableDelete(item: any) {
    const { id } = item
    this.httpPostGoodsType(`${id}/2`, {})
  }

  // 编辑
  onTableEdit(item: any, level: number) {
    const { id, name, userType, status, pid, url, icon, type, params, sort, platform } = item
    this.modalForm = {
      type: '1'
    }
    this.bUserType = userType == 0 || userType == 2
    this.cUserType = userType == 0 || userType == 1
    const userTypeStr = [0, 1, 2].includes(userType) ? `${userType}` : ''
    if (level == 1) {
      this.modalForm = { id, name, userType: userTypeStr, status, icon, type: `${type}`, url, platform, sort }
      // 设置适用终端
      this.channelChecked = platform ? platform.split(',') : [];
      this.channeloptions.forEach((ele: any) => {
        if (platform === '0') {
          ele.checked = true;
        } else {
          if (this.channelChecked.includes(ele.value)) {
            ele.checked = true;
          } else {
            ele.checked = false;
          }
        }
      });
      // 适用终端全选or全不选
      if (this.channeloptions.every((item: any) => !item.checked)) {
        this.terminalAllChecked = false;
        this.terminalIndeterminate = false;
      } else if (this.channeloptions.every((item: any) => item.checked)) {
        this.terminalAllChecked = true;
        this.terminalIndeterminate = false;
      } else {
        this.terminalIndeterminate = true;
      };

      this.isOneModalShow = true
    }
    if (level == 2) {
      this.modalForm = { id, pid: `${pid}`, name, userType: userTypeStr, status, sort, platform }
      this.httpCategoryParent(1) // 上级分类 取一级数据
      this.isTwoModalShow = true
    }
    if (level == 3) {
      this.modalForm = { id, userType: '0', pid: `${pid}`, name, url, params, icon, type: `${type}`, status, sort, platform }
      this.httpCategoryParent(2)// 级分类 取二级数据
      this.isThreeModalShow = true;

      // 三级链接下拉后CheckBox
      this.urlChecked = item.type === 4 ? true : false;
      if (item.type === 4) {
        this.modalForm.url = '-1';
        this.modalForm.params = '';
      }
    }
  }
  // 指定商品
  oninputLink(ev: any) {
    const { type } = this.modalForm
    if (type == 1) {
      this.timeout = setTimeout(() => {
        this.modalForm.url = ev.target.value.replace(/[^\d]/g, '')
        clearTimeout(this.timeout)
      }, 300);

    }
  }
  // 新增 确定提价数据
  async onConfirm(level: number) {
    const { id } = this.modalForm
    if (this.channelChecked?.length === this.channeloptions?.length) {
      this.modalForm.platform = '0';
    } else {
      this.modalForm.platform = this.channelChecked.join(',');
    }

    if (level == 1 && this.checkOne()) {
      return
    }
    if (level == 2 && this.checkTwo()) {
      return
    }
    if (level == 3 && this.checkThree()) {
      return
    }

    if (level == 1 && (this.commonService.isEmpty(this.modalForm.url) || this.modalForm.url === 'undefined')) {
      this.modalForm.url = '';
    }
    if (level == 2 || level == 3) {
      this.modalForm.platform = '0';
    }
    if (level === 3 && (this.modalForm.params == undefined || this.modalForm.params == null || this.modalForm.params == '')) {
      delete this.modalForm.params
    }

    const formData = new FormData()
    for (const iterator in this.modalForm) {
      formData.append(iterator, this.modalForm[iterator])
    }
    let isSuccess = null
    // console.log('21212121212', this.modalForm);
    // return
    if (id) {
      // 编辑
      isSuccess = await this.httpPutGoodsType(id, formData)
    } else {
      // 新增保存
      isSuccess = await this.httpPostGoodsType(level, formData)
    }
    if (isSuccess) {
      this.onModalClose() // 关闭弹窗
    }

  }

  // 分类一校验
  checkOne() {
    const { name, userType, status } = this.modalForm
    if (!name) {
      this.message.warning('请输入名称')
      return true
    }
    if (!userType) {
      this.message.warning('请选择适用用户')
      return true
    }
    if (![0, 1].includes(status)) {
      this.message.warning('请选择状态')
      return true
    }
    return false
  }

  // 分类二校验
  checkTwo() {
    const { pid, name, userType, status } = this.modalForm
    if (!pid) {
      this.message.warning('请选择上级分类')
      return true
    }
    if (!name) {
      this.message.warning('请输入名称')
      return true
    }
    if (!userType) {
      this.message.warning('请选择适用用户')
      return true
    }
    if (![0, 1].includes(status)) {
      this.message.warning('请选择状态')
      return true
    }
    return false
  }

  // 分类三校验
  checkThree() {
    const { pid, name, url, icon, type, status } = this.modalForm
    if (!pid) {
      this.message.warning('请选择上级分类')
      return true
    }
    if (!name) {
      this.message.warning('请输入名称')
      return true
    }
    if (!icon) {
      this.message.warning('请输入图标')
      return true
    }
    // if (!type) {
    //   this.message.warning('请选择跳转方式')
    //   return true
    // }
    // if (!url && type != 4) {
    //   this.message.warning(`请输入${this.typeSet[this.modalForm.type] || '链接'}`)
    //   return true
    // }
    if (![0, 1].includes(status)) {
      this.message.warning('请选择状态')
      return true
    }
    return false
  }
  /**
     * 查询列表
     * @returns
     */
  async httpList() {
    this.createBasicMessage()
    try {
      const { data }: any = await this.AppManagementService.httpGetGoodsType(this.queryForm)
      if (data) {
        this.tableData = data
        this.tableData?.records?.forEach((item: any) => {
          item.isShow = true
          item?.list?.forEach((element: any) => {
            element.isShow = true
          });
        });
      }
      this.removeBasicMessage()
    } catch (error) {
      this.removeBasicMessage()
    }
  }
  /**
   * 图片 上传
   * @returns
  */
  async httpUpload(originFileObj: any) {
    if (!originFileObj || this.forbidUpload) { // 禁止 重复上传
      return
    }
    this.forbidUpload = true
    try {
      const { data }: any = await this.AppManagementService.httpPostFile(originFileObj)
      this.modalForm.icon = data
      this.forbidUpload = false
      data && this.message.success('图片上传成功')
    } catch (error) {
      this.forbidUpload = false
      this.message.warning('图片上传失败，请重新选取上传')
    }
  }
  /**
   * 提交新增弹窗的数据
   * @returns
  */
  async httpPostGoodsType(query: any, params: any) {
    if (!params) {
      return
    }
    try {
      const { message }: any = await this.AppManagementService.httpPostGoodsType(query, params)
      message && this.message.success(message)
      if (message == 'success') {
        this.time = setTimeout(() => {
          this.queryForm.pageNum = 1
          this.httpList() // 成功刷新列表
          clearTimeout(this.time)
        }, 500);
      }
      return message == 'success'
    } catch (error) {
      console.log(error, 'error')
      return false;

    }
  }

  /**
   * 提交新增弹窗的数据
   * @returns
  */
  async httpPutGoodsType(query: any, params: any) {
    if (!params) {
      return
    }
    try {
      const { message }: any = await this.AppManagementService.httpPutGoodsType(query, params)
      message && this.message.success(message)
      if (message == 'success') {
        this.time = setTimeout(() => {
          this.httpList() // 成功刷新列表
          clearTimeout(this.time)
        }, 500);
      }
      return message == 'success'
    } catch (error) {
      console.log(error, 'error')
      return false;

    }
  }
  /**
  * 上级分类 下拉列表
  * @returns
 */
  async httpCategoryParent(query: any) {
    if (!query) {
      return
    }
    try {
      const { data }: any = await this.AppManagementService.httpCategoryParent(query)
      if (data) {
        this.categoryList = data
      }
    } catch (error) {
      console.log(error, 'error')

    }
  }

  // 状态 code转换中文
  status_to_text(val: number) {
    const text: any = { 0: '禁用', 1: '启用' }
    return text[val] || '-'
  }

  // 适用用户 code转换中文
  userType_to_text(val: number) {
    const text: any = { 0: '通用', 1: 'C端', 2: 'B端' }
    return text[val] || '-'
  }

  // 跳转方式 code转换中文
  type_to_text(val: number) {
    return this.typeSet[val] || '-'
  }

  /**
   * 上移下移
   * @param num 1：上移，2：下移
   * @param id
   */
  tableMoveUp(num: number, id: any) {
    if (num == 1) {
      this.AppManagementService.moveupTable(id).subscribe((res: any) => {
        if (res.code == 0) {
          this.createMessage('success', '操作成功');
        } else {
          this.createMessage('error', '操作失败');
        }
      }, (error: any) => {
        this.createMessage('error', '操作失败');
      })
    } else {
      this.AppManagementService.moveDownTable(id).subscribe((res: any) => {
        if (res.code == 0) {
          this.createMessage('success', '操作成功');
        } else {
          this.createMessage('error', '操作失败');
        }
      }, (error: any) => {
        this.createMessage('error', '操作失败');
      })
    }
    this.httpList();
  }

  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
  }
  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }
  /**
  * 全局展示操作反馈信息
  * @param type 其他提示类型 success:成功 error:失败 warning:警告
  */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }

  // 三级分类链接 checkbox change
  urlCheckedChange(val: any) {
    this.modalForm.url = '';
    this.modalForm.params = '';
    if (val) {
      this.modalForm.url = '-1';
    }
  }

  /**
   * ----------------------------------------------------------------
   * 关联 | 移除商品
   * ----------------------------------------------------------------
   */
  // 查询商品
  async getGoodsList() {
    let params = {
      name: this.goodTableParams.name,
      current: this.goodTableParams.page,
      size: this.goodTableParams.pageSize,
      delete: this.relationGoodType, // 是否是批量删除0代表否 1代表是
      operationType: this.relationGoodItem.id // 要批量新增或者删除商品的类型
    }
    const res: any = await this.AppManagementService.getGoodsListData(params);
    
    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.goodTable = records || [];
      this.goodTableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }
  // PageIndex Change
  goodIndexChange(index: number) {
    this.goodTableParams.page = index;
    this.getGoodsList();
  }
  // PageSize Change
  goodSizeChange(sizeNum: number) {
    this.goodTableParams.page = 1;
    this.goodTableParams.pageSize = sizeNum;
    this.getGoodsList();
  }

  searchGoodTable() {
    this.goodTableParams.page = 1;
    this.getGoodsList();
  }
  resetGoodTable() {
    this.goodTableParams.name = '';
    this.goodTableParams.page = 1;
    this.getGoodsList();
  }

  showRelationGoodsModal(item: any, type: number) {
    this.relationGoodItem = item;
    this.relationGoodType = type;
    this.setOfCheckedId.clear();
    this.setOfCheckedArr = [];

    this.goodTableParams.page = 1;
    this.getGoodsList();
    this.isRelationVisible = true;
  }

  relationCancel() {
    this.isRelationVisible = false;
  }

  subRelationData() {
    this.nzModal.confirm({
      nzTitle: `${this.relationGoodType === 0 ? '关联' : '移除'}提示`,
      nzContent: `确认将<b>${this.setOfCheckedId.size}</b>个商品${this.relationGoodType === 0 ? '关联到' : '移除于'}<b>(${this.relationGoodItem?.name})</b>分类下?`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.subbRelationInterface();
      },
      nzCancelText: '取消'
    });
  }
  async subbRelationInterface() {
    let tempArrs: any = []; // 对象数组 [{"id":商品id,"type":分类id}]
    this.setOfCheckedArr.forEach((item: any) => {
      tempArrs.push({
        id: item.id,
        type: this.relationGoodItem.id
      })
    })
    let params = {
      delete: this.relationGoodType, // 是否是批量删除 0、添加 1、删除
      list: tempArrs
    }
    
    this.subRelationGoodLoading = true;
    const res: any = await this.AppManagementService.updateRelationGoods(params);
    this.subRelationGoodLoading = false;
    if (res.code === 0) {
      this.message.success('操作成功');
      this.isRelationVisible = false;
      this.httpList();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 商品勾选 Table
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);

      let obj = this.listOfCurrentPageData.find((item: any) => item.id === id);
      this.setOfCheckedArr.push(obj);
    } else {
      this.setOfCheckedId.delete(id);

      let deleteIndex = this.setOfCheckedArr.findIndex((item: any) => item.id === id);
      this.setOfCheckedArr.splice(deleteIndex, 1);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  // 映射链接备注Filter
  remarkFilter(key: any) {
    let tempObj: any = this.mappingOptions.find((item: any) => {
      return item?.key === key
    })
    return tempObj?.remarks || '';
  }
}
